<?php

namespace app\controller\adminapi\open;

use app\common\model\open\Open;
use app\common\model\platform\PlatformAppOpen;
use app\common\services\table\DataTable;
use hiduoke\controller\AdminController;
use hiduoke\services\CloudServer;
use FormBuilder\Driver\CustomComponent;
use hiduoke\services\FormBuilder as Form;

class WeChatMini extends AdminController
{
    /**
     * @var PlatformAppOpen
     */
    public $model;

    /**
     * @var CloudServer
     */
    public $cloud;

    public function initialize()
    {
        $this->model = new Open();
        $this->cloud = new CloudServer();
    }

    public function getMinAppOpenList()
    {
        $res = $this->model->getPageList();
        return $this->success($res['count'], $res['data']);
    }

    /**
     * 微信小程序服务商管理端配置
     * @param $id
     * @param $type
     * @return \think\response\Json
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function form($id = 0, $type = 'wx')
    {
        $rule = array();
        //创建表单
        $row = $this->model->findOrEmpty($id); //创建表单
        $form = Form::createForm("/adminapi/open/weChatMini/save?id=" . $id)->setMethod("POST");
        //新增表单
        $rule[] = Form::input('name', '应用名称', $row['name'] ?? "")->required();
        $rule[] = Form::dkImage('logo', '应用图标', $row['logo'] ?? "")->required();
        $rule[] = Form::hidden('type', 'wx');
        //第三方平台信息
        $rule[] = Form::input("config_app_id", " AppID", $row['config']['app_id'] ?? '')->effect(['help' => '微信开放平台第三方平台 AppID'])->required();
        $rule[] = Form::input('config_secret', ' AppSecret', $row['config']['secret'] ?? '')->effect(['help' => '微信开放平台第三方平台 AppSecret'])->required();
        // 授权流程相关
        $rule[] = Form::input("config_token", "消息校验 Token", $row['config']['token'] ?? '')->effect(['help' => '用于验证消息来源的 Token，长度为 3-32 个字符，由字母和数字组成'])->required();
        $rule[] = Form::input("config_aes_key", "消息加解密密钥", $row['config']['aes_key'] ?? '')->effect(['help' => '用于消息加解密，长度固定为 43 个字符，由字母和数字组成'])->required();
        if ($id) {
            $oauth_url = request()->domain() . '/wxmin/open/event/id/' . $id;
            $message_event_url = request()->domain() . '/wxmin/open/message_event/id/' . $id . '/appid/$APPID$';
        } else {
            $oauth_url = "请提交保存后打开";
            $message_event_url = "请提交保存后打开";
        }
        $rule[] = Form::dkCopyInput("oauth_url", '授权事件接收', $oauth_url)
            ->effect(['help' => '将当前地址填写至微信开放平台第三方平台设置中的授权事件接收 URL，用于接收授权成功、取消授权等通知'])
            ->disabled(true);
        // 授权后实现业务
        $rule[] = Form::dkCopyInput("message_event_url", '消息与事件接收', $message_event_url)
            ->effect(['help' => '将当前地址填写至微信开放平台第三方平台设置中，用于接收已授权小程序的消息和事件推送'])
            ->disabled(true);
        $title = !$id ? "新增" : "编辑";
        $form->setTitle($title)->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }


    public function table()
    {
        $DataTable = (new DataTable($this->model));
        if ($this->request->param('recycle')) {
            // 回收站
            $DataTable->field([$this->model->getPk(), 'delete_time']);
        }
        $column = $DataTable
            ->setFilterFields(['appsecret', 'config', 'other_data', 'addon_name', 'type'])
            ->setField('logo', ['render' => 'image'])
            ->setField('type', ['render' => 'slot'])
            ->setField('addon_name', ['render' => 'tag'])
            ->operation(['width' => '200px', 'render' => 'buttons', 'prop' => 'operation', 'label' => '操作'])->create();
        return $this->success('ok', ['column' => $column, 'pk' => $this->model->getPk()]);
    }

    public function index()
    {
        if ($this->request->param('select')) {
            return $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where(['type' => 'wx'])
            ->order($order)
            ->paginate($limit);
        return $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }

    public function save()
    {
        $id = input('id', 0);
        $row = $this->model->findOrEmpty($id);
        $formData = getFormData();
        $row->save($formData);
        if ($id) {
            return $this->success("保存成功1111");
        } else {
            return $this->success('新增成功2222');
        }
    }
}
